package util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.StarMicronics.StarIOSDK.logic.MyApplication;

public class Util_G {

	public static void debug(String str) {
		System.out.println(str);
	}

	public static void debug(int data) {
		System.out.println(data);
	}

	private static Toast myToast = null;

	/** 显示Toast */
	public static void DisplayToast(String str, int length) {
		// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();//会累计

		if (myToast == null) {
			myToast = Toast.makeText(MyApplication.getInstance(), str, length);
		}

		myToast.setText(str);
		myToast.setDuration(length);
		myToast.show();
	}

	public static void DisplayToast(int resId, int length) {
		// TODO Auto-generated method stub
		if (myToast == null) {
			myToast = Toast.makeText(MyApplication.getInstance(), MyApplication.getInstance().getString(resId), length);
		}

		myToast.setText(MyApplication.getInstance().getString(resId));
		myToast.setDuration(length);
		myToast.show();
	}

	/** 获取资源文件的字符串 */
	public static String getString(int resId) {
		return MyApplication.getInstance().getResources().getString(resId);

	}

	/***
	 * 
	 * @param path
	 *            图片路径
	 * @param screenWidth
	 *            规定宽度
	 * @param newHeight
	 *            规定高度
	 * @param quality
	 *            压缩质量
	 */
	public static byte[] CompressBitmap(String path, int maxWidth, int maxHeight, int quality) {
		// get the picture from location
		Bitmap bitmap = null;
		try {
			/*-----长宽---*/
			BitmapFactory.Options opts = new BitmapFactory.Options();
			BitmapFactory.decodeFile(path, opts);
			int srcWidth = opts.outWidth;
			int srcHeight = opts.outHeight;
			int desWidth = 0;
			int desHeight = 0;
			// 缩放比例
			double ratio = 0.0;
			if (maxWidth > 0 && maxHeight > 0) {// 固定宽高等比缩放
				if (srcWidth > srcHeight) {
					ratio = srcWidth / maxWidth;
					desWidth = maxWidth;
					desHeight = (int) (srcHeight / ratio);
				} else {
					ratio = srcHeight / maxHeight;
					desHeight = maxHeight;
					desWidth = (int) (srcWidth / ratio);
				}
				// 设置输出宽度、高度
				BitmapFactory.Options newOpts = new BitmapFactory.Options();
				newOpts.inSampleSize = (int) (ratio) + 1;
				newOpts.inJustDecodeBounds = false;
				newOpts.outWidth = desWidth;
				newOpts.outHeight = desHeight;
				bitmap = BitmapFactory.decodeFile(path, newOpts);
			} else {
				if (maxWidth > 0 && maxWidth <= srcWidth) {
					ratio = srcWidth / maxWidth;
					desWidth = maxWidth;
					desHeight = (int) ((maxWidth * srcHeight) / srcWidth);
				} else if (maxHeight > 0 && maxHeight <= srcHeight) {
					ratio = srcHeight / maxHeight;
					desHeight = maxHeight;
					desWidth = (int) (maxHeight * srcWidth / srcHeight);
				}
				if ((maxWidth > 0 && srcWidth > maxWidth) || (maxHeight > 0 && srcHeight > maxHeight)) {
					BitmapFactory.Options newOpts = new BitmapFactory.Options();
					newOpts.inSampleSize = (int) (ratio) + 1;
					newOpts.inJustDecodeBounds = false;
					newOpts.outWidth = desWidth;
					newOpts.outHeight = desHeight;
					bitmap = BitmapFactory.decodeFile(path, newOpts);
				} else {
					bitmap = BitmapFactory.decodeFile(path);
				}
			}

			/*-----质量---*/
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			Boolean didItWork = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
			if (didItWork) {
				final byte[] ba = outStream.toByteArray();
				outStream.close();
				return ba;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * byte 转换为 kb MB
	 * 
	 */
	public static String bytes2kb(long bytes) {
		BigDecimal filesize = new BigDecimal(bytes);
		BigDecimal megabyte = new BigDecimal(1024 * 1024);
		float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
		if (returnValue > 1)
			return (returnValue + "  MB ");
		BigDecimal kilobyte = new BigDecimal(1024);
		returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
		return (returnValue + "  KB ");
	}

	/**
	 * 加粗字体
	 * 
	 * @param resId
	 * @return
	 */
	public static Spanned setTextColor(int resId, String... str) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		for (String string : str) {
			sb.append(string);
		}
		return Html.fromHtml("<font color='#000000'>" + MyApplication.getInstance().getString(resId) + "</font>" + sb.toString());
	}

	/**
	 * 加粗字体
	 * 
	 * @param resId
	 * @return
	 */
	public static Spanned setFontBold(int resId, String... str) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		for (String string : str) {
			sb.append(string);
		}
		return Html.fromHtml("<font color='#000000'><b><big>" + MyApplication.getInstance().getString(resId) + "</big></b></font>" + sb.toString());
	}

	/**
	 * 加粗字体
	 * 
	 * @param resId
	 * @return
	 */
	public static Spanned setFontBold(String str, String... str1) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		for (String string : str1) {
			sb.append(string);
		}
		return Html.fromHtml("<font color='#000000'><b><big>" + str + "</big></b></font>" + sb.toString());
	}

	/**
	 * 加粗字体
	 * 
	 * @param resId
	 * @return
	 */
	// public static Spanned setFontBoldOrder(String str) {
	// // TODO Auto-generated method stub
	// return Html.fromHtml("<b><big>" + str + "</big></b>");
	// }

	// /**
	// * 加粗字体
	// *
	// * @param resId
	// * @return
	// */
	// public static Spanned setFontBoldOrder(int resId) {
	// // TODO Auto-generated method stub
	// return Html.fromHtml("<b><big>" +
	// MyApplication.getInstance().getString(resId) + "</big></b>");
	// }

	/**
	 * 加粗字体
	 * 
	 * @param resId
	 * @return
	 */
	public static Spanned setFontBoldColor(String str, String... str1) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		for (String string : str1) {
			sb.append(string);
		}
		return Html.fromHtml("<big>" + str + "</big>" + sb.toString());
	}

	/**
	 * 加粗字体
	 * 
	 * @param resId
	 * @return
	 */
	public static Spanned setFontBoldColor(int resId, String... str1) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		for (String string : str1) {
			sb.append(string);
		}
		return Html.fromHtml("<big>" + MyApplication.getInstance().getString(resId) + "</big>" + sb.toString());
	}

	public static String strAddStr(String... strings) {
		StringBuffer sb = new StringBuffer();
		for (String string : strings) {
			sb.append(string);
		}
		return sb.toString();
	}

	public static String strAddStr(int... strings) {
		StringBuffer sb = new StringBuffer();
		for (int string : strings) {
			sb.append(string);
		}
		return sb.toString();
	}

	public static byte[] stringArray2byteArray(String[] content) {

		if (content == null || content.length <= 0)
			return null;

		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		DataOutputStream dOut = new DataOutputStream(byteOut);
		byte[] data = null;
		try {

			for (int i = 0, content_size = content.length; i < content_size; i++) {
				if (content[i] == null) {
					dOut.writeUTF("null");
				} else {
					dOut.writeUTF(content[i]);
				}
			}
			data = byteOut.toByteArray();
			dOut.close();
			byteOut.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return data;
	}

	public final static String utf8Decode(byte[] utf8_bytes) {
		try {
			return (new String(utf8_bytes, "UTF-8"));
		} catch (Exception e) {
			return null;
		}
	}

	public final static byte[] utf8Encode(String utf8_str) {
		try {
			return (utf8_str.getBytes("UTF-8"));
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @param ins
	 * @param MAXLEN
	 *            默认值-1
	 * @return
	 */
	public static byte[] getByteArrayFromInputstream(InputStream ins, int MAXLEN) {

		if (MAXLEN == -1)
			MAXLEN = 30000;

		try {

			byte[] charset = new byte[MAXLEN];
			int ch = ins.read();
			int length = 0;
			while (ch != -1) {
				charset[length] = (byte) ch;
				ch = ins.read();
				length++;
			}
			byte[] xmlCharArray = new byte[length];
			System.arraycopy(charset, 0, xmlCharArray, 0, length);

			return (xmlCharArray);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public final static String replace(String content, String olds, String news) {
		int index = 0;
		while (true) {
			index = content.indexOf(olds, index);
			if (index == -1)
				break;
			content = content.substring(0, index) + news + content.substring(index + olds.length());
			index += news.length();
		}
		return content;
	}

	public static int dip2px(float dipValue) {
		Context context = MyApplication.getInstance();
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);

	}

	public static int px2dip(float pxValue) {
		Context context = MyApplication.getInstance();
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static Bitmap getBitmapFromID(int R_ID) {
		Bitmap bmp = ((BitmapDrawable) MyApplication.getInstance().getResources().getDrawable(R_ID)).getBitmap();
		return bmp;
	}

	public static Bitmap getBitmapFromID_1(int R_ID) {
		Bitmap bitmap = BitmapFactory.decodeResource(MyApplication.getInstance().getResources(), R_ID);
		return bitmap;
	}

	public static int getImageHeightFromID(int R_ID) {
		Bitmap bitmap = getBitmapFromID(R_ID);
		return bitmap.getHeight();
	}

	public static int getImageWeightFromID(int R_ID) {
		Bitmap bitmap = getBitmapFromID(R_ID);
		return bitmap.getWidth();
	}

	public static Bitmap getImageForBytes(byte[] btm) {
		Bitmap bitmap = BitmapFactory.decodeByteArray(btm, 0, btm.length);
		return bitmap;

	}

	public static boolean isNullStr(String str) {
		if (str == null || str.length() <= 0)
			return true;
		return false;
	}

	public static String getDateTime() {
		Calendar calendar = Calendar.getInstance();

		String time = Util_G.strAddStr(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
		return time;
	}

	// 获取标准时间
	public static String getLoactionTime() {
		java.util.Date current = new java.util.Date();
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(current);

	}

	// 获取标准时间
	public static String getLoactionTime(String str) {
		SimpleDateFormat sdfTimeb = new SimpleDateFormat("yyyy/MM/dd EE HH:mm");
		SimpleDateFormat sdfTimeb1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date;
		try {
			date = sdfTimeb1.parse(str);
			return sdfTimeb.format(date);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	// 获取标准时间
	public static String getSwitchTime(String str) {
		SimpleDateFormat sdfTimeb = new SimpleDateFormat("yyyy'年'MM'月'dd'日'");
		SimpleDateFormat sdfTimeb1 = new SimpleDateFormat("yyyy/MM/dd");
		Date date;
		try {
			date = sdfTimeb1.parse(str);
			return sdfTimeb.format(date);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	// 获取标准时间
	public static String getSwitchTime01(String str) {
		SimpleDateFormat sdfTimeb = new SimpleDateFormat("yyyy/MM/dd");
		SimpleDateFormat sdfTimeb1 = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = sdfTimeb1.parse(str);
			return sdfTimeb.format(date);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	private static URL url;
	private static HttpURLConnection con;
	private static int state = -1;

	/**
	 * 功能：检测当前URL是否可连接或是否有效, 描述：最多连接网络 5 次, 如果 5 次都不成功，视为该地址不可用
	 * 
	 * @param urlStr
	 *            指定URL网络地址
	 * @return URL
	 */
	public synchronized static boolean isConnect(String urlStr) {
		int counts = 0;
		if (urlStr == null || urlStr.length() <= 0) {
			return false;
		}
		while (counts < 2) {
			try {
				url = new URL(urlStr);
				con = (HttpURLConnection) url.openConnection();
				state = con.getResponseCode();
				if (state == 200) {
					return true;
				}
				break;
			} catch (Exception ex) {
				counts++;
				System.out.println("URL不可用，连接第 " + counts + " 次");
				urlStr = null;
				continue;
			}
		}
		return false;
	}

	public static String getResult(String jsonStr) throws JSONException {
		JSONObject jsonObject = new JSONObject(jsonStr);
		jsonStr = jsonObject.getString("responseStatus");
		// Util_G.debug("responseStatus---"+jsonObject.toString());
		return jsonStr;
	}

	/**
	 * 压缩图片，宽度固定
	 * 
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static byte[] CompressBitmap_(String path, int w, int h, int quality) {
		try {
			Bitmap bitmapOrg = BitmapFactory.decodeFile(path);
			int srcWidth = bitmapOrg.getWidth();
			int srcHeight = bitmapOrg.getHeight();
			System.out.println("AFTER. Height: " + srcHeight + " Width: " + srcWidth);
			int newWidth = w;
			int newHeight = h;
			if (srcWidth >= w) {
				// calculate the scale
				float scaleWidth = ((float) newWidth) / srcWidth;
				@SuppressWarnings("unused")
				float scaleHeight = ((float) newHeight) / srcHeight;
				// create a matrix for the manipulation
				Matrix matrix = new Matrix();
				matrix.postScale(scaleWidth, scaleWidth);
				bitmapOrg = Bitmap.createBitmap(bitmapOrg, 0, 0, srcWidth, srcHeight, matrix, true);
			}
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			Boolean didItWork = bitmapOrg.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
			if (didItWork) {
				System.out.println("AFTER. Height: " + bitmapOrg.getHeight() + " Width: " + bitmapOrg.getWidth());
				final byte[] ba = outStream.toByteArray();
				System.out.println("file--->>><<>" + bytes2kb(outStream.size()));
				outStream.close();
				return ba;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 图片截取
	 * 
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap cutImage(Bitmap bitmap, int screenWidth, int newHeight) {
		if (bitmap != null) {
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();
			int newWidth = screenWidth;
			if (width < screenWidth) {
				return bitmap;
			}
			// calculate the scale
			float scaleWidth = ((float) newWidth) / width;
			@SuppressWarnings("unused")
			float scaleHeight = ((float) newHeight) / height;
			// create a matrix for the manipulation
			Matrix matrix = new Matrix();
			// resize the Bitmap
			// matrix.postScale(scaleWidth, scaleHeight);
			matrix.postScale(scaleWidth, scaleWidth);
			// if you want to rotate the Bitmap
			// matrix.postRotate(45);
			// recreate the new Bitmap
			Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, newHeight, matrix, true);
			// Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
			// screenWidth, 100);
			return resizedBitmap;
		}
		return null;
	}

	/**
	 * 压缩图片，宽度固定
	 * 
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {

		// load the origial Bitmap
		Bitmap BitmapOrg = bitmap;
		if (BitmapOrg != null) {
			int width = BitmapOrg.getWidth();
			int height = BitmapOrg.getHeight();
			int newWidth = w;
			int newHeight = h;
			if (width <= w) {
				return bitmap;
			}
			// calculate the scale
			float scaleWidth = ((float) newWidth) / width;
			@SuppressWarnings("unused")
			float scaleHeight = ((float) newHeight) / height;
			// create a matrix for the manipulation
			Matrix matrix = new Matrix();
			// resize the Bitmap
			// matrix.postScale(scaleWidth, scaleHeight);
			matrix.postScale(scaleWidth, scaleWidth);
			// if you want to rotate the Bitmap
			// matrix.postRotate(45);
			// recreate the new Bitmap
			Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			resizedBitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
			// bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
			// make a Drawable from Bitmap to allow to set the Bitmap
			// to the ImageView, ImageButton or what ever
			// return new BitmapDrawable(resizedBitmap);
			return resizedBitmap;
		}
		return null;
	}

	/***
	 * 根据Uri字符串获取图片名字
	 * 
	 * @param uri
	 * @return
	 */
	public static String getNameFromUri(String uri) {
		return uri.substring(uri.lastIndexOf("/") + 1, uri.length());
	}

	/* 根据自定义的名字获取定义在strings中的数据库 */
	public static String[] getRessouseArray(String stringArrayName) {
		String[] planets = null;
		try {
			int id = MyApplication.getInstance().getResources().getIdentifier(stringArrayName, "array", MyApplication.getInstance().getPackageName());
			planets = MyApplication.getInstance().getResources().getStringArray(id);
		} catch (Exception e) {
			System.out.println("error!!!");
		}
		return planets;

	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	public static boolean isExtStorageAvailable() {
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * get the version
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersion(Context context) {
		String version;
		try {
			version = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA).versionName;
		} catch (NameNotFoundException e) {
			version = "UnknownVersion";
		}
		return version;
	}

	@SuppressWarnings("resource")
	public static void copyFile(File src, File dst) throws IOException {
		FileChannel inChannel = new FileInputStream(src).getChannel();
		FileChannel outChannel = new FileOutputStream(dst).getChannel();
		try {
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} finally {
			if (inChannel != null) {
				inChannel.close();
			}
			if (outChannel != null) {
				outChannel.close();
			}
		}
	}

	private static final int DEFAULT_BUFFER_SIZE = 8192;

	public static int copy(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
		int count = 0;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}

	/****
	 * get the current sdk version
	 * 
	 * @return
	 */
	public static int getSDKVersionNumber() {
		int sdkVersion;
		try {
			sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			sdkVersion = 0;
		}
		return sdkVersion;
	}

	/***
	 * whether it is int
	 * 
	 * @param strInt
	 * @return
	 */
	public static boolean isNumeric(String strInt) {
		if (strInt == null || strInt == "")
			return false;
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(strInt);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/***
	 * whether it is Chinese Character
	 * 
	 * @param strInt
	 * @return
	 */
	public static boolean isChineseCharacter(String str) {
		Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]*$");
		Matcher matcher = pattern.matcher(str);
		if (matcher.find()) {
			return true;
		}
		return false;
	}

	/**
	 * 深拷贝 Model 需要实现Serializable接口，可以序列化
	 * 
	 * 对拷贝后的引用的修改，还能影响原来的对象
	 * 
	 * 对现在对象的修改不会影响原有的对象
	 * 
	 * @param src
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("rawtypes")
	static public List deepCopy(List src) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(byteOut);
		out.writeObject(src);
		ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		List dest = (List) in.readObject();
		return dest;
	}

	// 登录判断
	public static boolean isEmail(String email) {
		if (!email.contains("@")) {
			return false;
		}
		String str = email.substring(email.indexOf("@") + 1, email.length());
		if (str.contains(".")) {
			return true;
		} else {
			return false;
		}
	}

}
